package com.iwhalecloud.bss.kite.cucc.service.customerOrderInformation;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import javax.annotation.Resource;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iwhalecloud.bss.hsf.baseinf.service.InfExchangeService;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.JsonUtils;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.IUnicomRegionService;
import com.iwhalecloud.bss.kite.cucc.client.api.customerOrderInformation.ICustomerOrderInfoService;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IOrderService;
import com.iwhalecloud.bss.kite.cucc.client.api.reception.ICustReceptionService;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegion;
import com.iwhalecloud.bss.kite.cucc.client.dto.customerOrderInformation.CustOrderInfoRegion;
import com.iwhalecloud.bss.kite.cucc.client.dto.customerOrderInformation.CustomerOrderInformationReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.customerOrderInformation.OrderRejectionCust;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.ProdInstQryDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.UserQueryDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDetailDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.UserInfomationDTO;
import com.iwhalecloud.bss.kite.cucc.client.enumerate.OrgLevel;
import com.iwhalecloud.bss.kite.cucc.common.callclient.HttpsCallClient;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalCallClientEnum;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalInfConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.CommonUtil;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.UnicomRegionCache;
import com.iwhalecloud.bss.kite.cucc.service.inf.InfServiceHelper;
import com.iwhalecloud.bss.kite.cucc.service.util.LocalTokenUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.AttrValue;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.ztesoft.bss.common.bo.LoginInfo;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.DateUtil;
import com.ztesoft.bss.common.util.SpringUtil;

@Transactional(rollbackFor = Exception.class)
@Service
public class CustomerOrderInfoService implements ICustomerOrderInfoService {

    @Value("${interface.call.mode:hsf}")
    private String mode;

    @Autowired
    private ICustReceptionService custReceptionService;

    @Resource
    private IUnicomRegionService unicomRegionService;

    @Autowired
    private IOrderService orderService;

    @Override
    public PageInfo<CuccCustInfoDTO> selectCustomerOrderInformation(
        CustomerOrderInformationReq customerOrderInformationReq) {

        /*KiteCustomerInfoReq kiteCustomerInfoReq = new KiteCustomerInfoReq();
        KiteBeanUtils.copyProperties(customerOrderInformationReq, kiteCustomerInfoReq);
        PageInfo<CuccCustInfoDTO> cuccCustInfoDTOPageInfo = this.custReceptionService
            .customerListQueryNew(kiteCustomerInfoReq);
        return cuccCustInfoDTOPageInfo;*/

        LoginInfo login = ContextUtil.getLoginInfo();
        String provinceCode = KiteStringUtils.isEmpty(customerOrderInformationReq.getProvinceCode()) ?
            login.getUserInfo().getPostProvinceNbr() : customerOrderInformationReq.getProvinceCode();
        String eparchyCode = customerOrderInformationReq.getEparchyCode();

        Map<String, Object> pageReq = new HashMap<>();
        pageReq.put("PAGE_SIZE", customerOrderInformationReq.getPageSize());
        pageReq.put("PAGE_NUM", customerOrderInformationReq.getPageNum());
//        pageReq.put("CUST_STATES", "0");
        //用户类别（不查个人客户‘0’,小微企业"1"）
        pageReq.put("CUST_CLASS_TYPE", "2,3,4,5");
        //cBSS客户编码
        pageReq.put("CUST_ID", customerOrderInformationReq.getCustId());
        //集团编码
        pageReq.put("GROUP_ID", customerOrderInformationReq.getGroupId());
        // 业务号码转成custId
        if (KiteStringUtils.isNotBlank(customerOrderInformationReq.getAccNum())) {
            String staffCode = (String) ContextUtil.getLoginInfo().getUserInfo().getExtParams().get("account");
            String custId = this.queryCustIdFromUserListByAccNum(customerOrderInformationReq.getAccNum(),
                staffCode, provinceCode, eparchyCode);
            if (KiteStringUtils.isNotBlank(custId) && (KiteStringUtils.isBlank(customerOrderInformationReq.getCustId())
                || KiteStringUtils.equals(custId, customerOrderInformationReq.getCustId()))) {
                pageReq.put("CUST_ID", custId);
            } else {
                return new PageInfo<>(new ArrayList<>());
            }
        }
        //集团客户名称
        pageReq.put("CUST_NAME", customerOrderInformationReq.getCustName());
        //省份编码
        pageReq.put("PROVINCE_CODE", provinceCode);
        //地市编码
        pageReq.put("EPARCHY_CODE", eparchyCode);

        Map<String, Object> tcpCont = new HashMap<>();

        Map<String, Object> operUserInfo = new HashMap<>();
        operUserInfo.put("USER_CODE", ContextUtil.getSimpleLoginInfo().getUserCode());
        operUserInfo.put("ROLE_ID", "0");

        pageReq.put("TCP_CONT", tcpCont);
        pageReq.put("OPER_USER_INFO", operUserInfo);

        Map<String, Object> uniBssBodyMap = new HashMap<>();
        uniBssBodyMap.put("PAGE_REQ", pageReq);

        Map<String, Object> param = LocalTokenUtil.getParamMap(uniBssBodyMap);
        PageHelper.startPage(customerOrderInformationReq.getPageNum(), customerOrderInformationReq.getPageSize());

        Map<String, Object> restultMap = HttpsCallClient.postObjMap(LocalCallClientEnum.QRY_CUSTOMER_LIST.getCenterCode(), LocalCallClientEnum.QRY_CUSTOMER_LIST.getServiceCode(), param, LocalTokenUtil.getHeaderMap());
        Map<String, Object> resultBodyMap = KiteMapUtils.getValue(restultMap, "UNI_BSS_BODY");
        Map<String, String> pageRsp = KiteMapUtils.getValue(resultBodyMap, "PAGE_RSP");
        List<CuccCustInfoDTO> cuccCustInfoDTOList = JsonUtils
            .parseArray(KiteMapUtils.getString(pageRsp, "DATA_LIST"), CuccCustInfoDTO.class);
        if (!KiteListUtils.isEmpty(cuccCustInfoDTOList)) {
            cuccCustInfoDTOList.stream().forEach(cuccCustInfoDTO -> {
                String custId = cuccCustInfoDTO.getCustId();
                cuccCustInfoDTO.setCbssId(custId);
                cuccCustInfoDTO.setEparchyName(cuccCustInfoDTO.getProvinceName() + "-" + cuccCustInfoDTO.getEparchyName());

                //客户组织机构代码
                if (KiteStringUtils.equals(cuccCustInfoDTO.getCertiTypeCode(), "S")) {
                    cuccCustInfoDTO.setCuccOrgCode(cuccCustInfoDTO.getCertiCode());
                }
            });
            PageInfo<CuccCustInfoDTO> pageInfo = new PageInfo<>(cuccCustInfoDTOList);
            long totalRow = KiteMapUtils.getLongValue(pageRsp, "TOTAL_ROW");
            pageInfo.setTotal(totalRow);
            int pageNum = customerOrderInformationReq.getPageNum();
            int pageSize = customerOrderInformationReq.getPageSize();
            pageInfo.setPageNum(pageNum);
            pageInfo.setPageSize(pageSize);
            int pages = (int) totalRow / pageSize;
            if (totalRow % pageSize != 0) {
                pages++;
            }
            pageInfo.setPages(pages);
            return pageInfo;
        }
        return new PageInfo<CuccCustInfoDTO>(new ArrayList<>());
    }

    /**
     * 根据业务号码获取客户id（调用户列表查询接口，一个业务号码可能对应多个用户，调用户详情报错）
     *
     * @param accNum
     * @return
     */
    public String queryCustIdFromUserListByAccNum(String accNum, String staffCode, String provinceCode, String eparchyCode) {
        Map<String, Object> uniBssBodyMap = new HashMap();
        Map<String, Object> reqMap = new HashMap();
        reqMap.put("STAFF_CODE", staffCode);
        reqMap.put("PROVINCE_CODE", provinceCode);
        reqMap.put("QRY_TYPE", "2");
        reqMap.put("PAGE_NUM", "1");
        reqMap.put("PAGE_SIZE", "10");
        reqMap.put("SERIAL_NUMBER", accNum);
        reqMap.put("IS_EFFECTIVE", "0"); // 是否查询生效用户（0：全部；1：生效）
        reqMap.put("QRY_SOURCE", "2"); // 是否查询老集客（1：都查；2：用户中心）
        reqMap.put("USER_KIND", "1"); // 只查非成员用户

        //tcpCont
        Map<String, String> tcpContMap = new HashMap();
        tcpContMap.put("APP_KEY", LocalInfConsts.APP_ID);
        tcpContMap.put("TRANS_ID", LocalTokenUtil.getTransId());
        reqMap.put("TCP_CONT", tcpContMap);
        uniBssBodyMap.put("REQ", reqMap);

        Map<String, Object> requestMap = LocalTokenUtil.getParamMap(uniBssBodyMap);
        requestMap.put("OP_CODE", "json_bbssUserCenter_SalBusaGrpUserSerApi_qryGrpUserList");
        InfServiceHelper.adaptGray(requestMap, reqMap);

        String result;
        if (KiteStringUtils.isEqual(mode, "http")) {
            result = HttpsCallClient
                .postStringWithObject(LocalCallClientEnum.INF_COMMON_URL, requestMap, LocalTokenUtil.getHeaderMap());
        } else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            result = infExchangeService.exchange(new JSONObject(requestMap));
        }

        Map<String, Object> rsp = JSON.parseObject(result, Map.class);
        Map<String, Object> uniBssHead = KiteMapUtils.getMap(rsp, "UNI_BSS_HEAD");
        if (!KiteStringUtils.equals(LocalInfConsts.RESP_SUCCESS, KiteMapUtils.getString(uniBssHead, "RESP_CODE"))) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("json_bbssUserCenter_SalBusaGrpUserSerApi_qryGrpUserList",KiteMapUtils.getString(uniBssHead, "RESP_DESC"));
        }
        Map<String, Object> rspUniBssBodyMap = KiteMapUtils.getMap(rsp, "UNI_BSS_BODY");
        if (KiteMapUtils.isEmpty(rspUniBssBodyMap)) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("json_bbssUserCenter_SalBusaGrpUserSerApi_qryGrpUserList","接口返回报文缺少UNI_BSS_BODY节点信息!");
        }

        Map<String, Object> rspMap = KiteMapUtils.getMap(rspUniBssBodyMap, "RSP");
        if (!KiteStringUtils.equals("0000", KiteMapUtils.getString(rspMap, "RSP_CODE"))) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("json_bbssUserCenter_SalBusaGrpUserSerApi_qryGrpUserList",KiteMapUtils.getString(rspMap, "RSP_DESC"));
        }

        Map<String, Object> qryGrpUserListMap = KiteMapUtils.getMap(rspMap, "QRY_GRP_USER_LIST_RSP_BODY");
        List<Map> userList = CommonUtil.getList(qryGrpUserListMap, "GROUP_USER_LIST");
        String custId = null;
        if(KiteListUtils.isNotEmpty(userList)) {
            custId = KiteMapUtils.getString(userList.get(0), "CUST_ID");
        }
        return custId;
    }

    @Override
    public Map<String, Object> selectUserInfomationByCustId(String custId, String accNum, String memAccNum, String userDiffCode,
                                                            String isSelfAccept, Integer pageNum, Integer pageSize,
                                                            String eparchyCode, String provinceCode) {

        Map<String, String> map = new HashMap<>(5);
        if (KiteStringUtils.isEqual(isSelfAccept, "0")) {
            map.put("openStaffId", (String) ContextUtil.getLoginInfo().getUserInfo().getExtParams().get("account"));
        }
        map.put("userDiffCode", userDiffCode);
        map.put("pageNum", pageNum.toString());
        if(KiteStringUtils.isNotEmpty(accNum)) {
            map.put("accNum", accNum);
        } else {
            map.put("custId", custId);
        }
        map.put("memAccNum", memAccNum);
        map.put("pageSize", pageSize.toString());
        map.put("provinceCode", provinceCode);
        map.put("eparchyCode", eparchyCode);
        map.put("isEffective", "0"); // 查询全部状态的用户列表进行展示
        UserQueryDTO userQueryDTO = this.queryUserList(map);

        //组装用户列表
        PageInfo<ProdInstQryDTO> userList = userQueryDTO.getUserList();

        List<UserInfomationDTO> userInfomationDTOS = KiteBeanUtils.copyPropsForList(userList.getList(), UserInfomationDTO.class);
        userInfomationDTOS.forEach(item -> {
            item.setMemberTotal(1);
        });
        userInfomationDTOS.forEach(user -> {
            if (KiteStringUtils.isEmpty(user.getUser_state_name())) {
                String userState = user.getUser_state();
                String userStateCodeName = "";
                if (KiteStringUtils.isNotEmpty(userState)) {
                    userStateCodeName = Optional.ofNullable(AttrValueCache.getAttrValue("2020012105", userState))
                        .map(AttrValue::getAttrValueName).orElse(userState);
                }
                user.setUser_state_name(userStateCodeName);
            }
            ICustReceptionService custReceptionService = SpringUtil.getBean(ICustReceptionService.class);
            CuccCustInfoDetailDTO custInfo = custReceptionService.getCustomerInfoNew(user.getCust_id());
            String provinceId = custInfo.getProvinceCode();
            String lanId = custInfo.getEparchyCode();
            String regionId = Optional.ofNullable(custInfo.getCityCode()).orElse(custInfo.getBcityCode());
            String province = Optional.ofNullable(UnicomRegionCache.getOneUnicomRegion(provinceId)).map(UnicomRegion::getRegionName).orElse("");
            String lan = Optional.ofNullable(UnicomRegionCache.getOneUnicomRegion(lanId)).map(UnicomRegion::getRegionName).orElse("");
            /**
             * 客户订购信息查询，增加regionId为空，不获取区域名称的判断,CustomerOrderInfoService.selectUserInfomationByCustId，避免由于客户末梢区域为空，导致报“regionCode must not be empty”；
             * 天梯任务id:16883
             * add  by ma.junjun  2022-01-20
             */
            String region ="";
            if(KiteStringUtils.isNotEmpty(regionId)){
                region = Optional.ofNullable(UnicomRegionCache.getOneUnicomRegion(regionId)).map(UnicomRegion::getRegionName).orElse("");
            }
            user.setLocation(new StringBuilder(province).append(lan).append(region).toString());
        });
        PageInfo<UserInfomationDTO> pageInfo = new PageInfo<>();
        pageInfo.setList(userInfomationDTOS);
        pageInfo.setPageNum(userList.getPageNum());
        pageInfo.setPageSize(userList.getPageSize());
        pageInfo.setPages(userList.getPages());
        pageInfo.setTotal(userList.getTotal());

        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("userList", pageInfo);
        userInfo.put("custInfo", userQueryDTO.getCustInfo());

        return userInfo;
    }

    @Override
    public UserQueryDTO queryUserList(Map<String, String> paramMap) {
        String userName = KiteMapUtils.getString(paramMap, "userName");
        String accNum = KiteMapUtils.getString(paramMap, "accNum");
        String custId = KiteMapUtils.getString(paramMap, "custId");
        String pageNum = KiteMapUtils.getString(paramMap, "pageNum");
        String pageSize = KiteMapUtils.getString(paramMap, "pageSize");
        String eparchyCode = KiteMapUtils.getString(paramMap, "eparchyCode");
        String provinceCode = KiteMapUtils.getString(paramMap, "provinceCode");
        String openStaffId = KiteMapUtils.getString(paramMap, "openStaffId");
        String userDiffCode = KiteMapUtils.getString(paramMap, "userDiffCode");
        String isEffective = KiteMapUtils.getString(paramMap, "isEffective");
        String memAccNum = KiteMapUtils.getString(paramMap, "memAccNum");

        UserQueryDTO userQueryDto = new UserQueryDTO();
        // FIXME: 工号相关信息不一定是当前登录工号信息，等用户中心接口落地了应该做出修改
        //省份编码
        /*if (KiteStringUtils.isEmpty(eparchyCode)) {
            eparchyCode = ContextUtil.getLoginInfo().getUserInfo().getPostLanId();
        }
        if (KiteStringUtils.isEmpty(provinceCode)) {
            provinceCode = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        }*/

        pageNum = !KiteStringUtils.isEmpty(pageNum) ? pageNum : "1";
        pageSize = !KiteStringUtils.isEmpty(pageSize) ? pageSize : "10";
        Integer intpageNum = Integer.parseInt(pageNum);
        Integer intPageSize = Integer.parseInt(pageSize);
        Map<String, Object> requestMap = new HashMap<String, Object>();
        requestMap.put("OP_CODE", "json_bbssUserCenter_SalBusaGrpUserSerApi_qryGrpUserList");
        Map<String, Object> uniBssBodyMap = new HashMap<String, Object>();
        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("USER_NAME", userName);
        reqMap.put("PROVINCE_CODE", provinceCode);
        reqMap.put("QRY_TYPE", "2");
        reqMap.put("SERVICE_TYPE_CODE", "");
        reqMap.put("OPEN_STAFF_ID", openStaffId);
        reqMap.put("PAGE_NUM", pageNum);
        reqMap.put("PAGE_SIZE", pageSize);
        reqMap.put("SERIAL_NUMBER", !KiteStringUtils.isEmpty(accNum) ? accNum : memAccNum);
        reqMap.put("QRY_SOURCE", "2");
        reqMap.put("CUST_ID", custId);

        if (!KiteStringUtils.isEmpty(accNum) && KiteStringUtils.isNotEmpty(userDiffCode)) {
            reqMap.put("USER_DIFF_CODE", userDiffCode);
        }
        if (KiteStringUtils.isNotEmpty(isEffective)) {
            reqMap.put("IS_EFFECTIVE", isEffective);
        }
        //tcpCont
        Map<String, String> tcpContMap = new HashMap<String, String>();
        tcpContMap.put("APP_KEY", "");
        tcpContMap.put("TRANS_ID", "");
        reqMap.put("TCP_CONT", tcpContMap);

        //para
        List<Map<String, String>> para = new ArrayList<Map<String, String>>();
        reqMap.put("PARA", para);
        uniBssBodyMap.put("REQ", reqMap);
        requestMap.put("UNI_BSS_BODY", uniBssBodyMap);
        InfServiceHelper.adaptGray(requestMap, reqMap);

        Map map;
        if (KiteStringUtils.isEqual(mode, "http")) {
            map = HttpsCallClient.postObjMap(LocalCallClientEnum.QRY_PRODINST_LIST.getCenterCode(),
                LocalCallClientEnum.QRY_PRODINST_LIST.getServiceCode(), requestMap, null);
        } else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            String resultStr = infExchangeService.exchange(new JSONObject(requestMap));
            map = JSON.parseObject(resultStr, Map.class);
        }

        Map<String, Object> unibssHeadMap = (Map<String, Object>) map.get("UNI_BSS_HEAD");
        if (!KiteStringUtils.equals(KiteMapUtils.getString(unibssHeadMap, "RESP_CODE"), LocalInfConsts.RESP_SUCCESS)) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("json_bbssUserCenter_SalBusaGrpUserSerApi_qryGrpUserList",KiteMapUtils.getString(unibssHeadMap, "RESP_DESC"));
        }

        Map<String, Object> rspUniBssBodyMap = (Map<String, Object>) map.get("UNI_BSS_BODY");

        if (KiteMapUtils.isEmpty(rspUniBssBodyMap)) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("json_bbssUserCenter_SalBusaGrpUserSerApi_qryGrpUserList","返回报文缺少UNI_BSS_BODY节点");
        }
        Map<String, Object> rspMap = (Map<String, Object>) rspUniBssBodyMap.get("RSP");
        if (!KiteStringUtils.equals(KiteMapUtils.getString(rspMap, "RSP_CODE"), "0000")) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("json_bbssUserCenter_SalBusaGrpUserSerApi_qryGrpUserList",KiteMapUtils.getString(rspMap, "RSP_DESC"));
        }
        Map<String, Object> qryGrpUserListMap = (Map<String, Object>) rspMap.get("QRY_GRP_USER_LIST_RSP_BODY");
        Integer rowCount = KiteMapUtils.getInteger(qryGrpUserListMap, "ROW_COUNT");

        List<JSONObject> groupUserList = (List<JSONObject>) qryGrpUserListMap.get("GROUP_USER_LIST");

        List<ProdInstQryDTO> prodInstDtoList = new ArrayList<ProdInstQryDTO>();

        if (KiteListUtils.isNotEmpty(groupUserList)) {
            groupUserList.forEach(item -> {
                ProdInstQryDTO prodInstQryDto = JSON.parseObject(item.toJSONString(), ProdInstQryDTO.class);

                //开户时间处理
                String openDate = prodInstQryDto.getOpen_date();
                Date dOpenDate = DateUtil.strToDate(openDate);
                openDate = DateUtil.format(dOpenDate);
                prodInstQryDto.setOpen_date(openDate);

                //销户时间处理
                String destroyDate = prodInstQryDto.getDistroy_time();
                Date dDestroyDate = DateUtil.strToDate(destroyDate);
                destroyDate = DateUtil.format(dDestroyDate);
                prodInstQryDto.setDistroy_time(destroyDate);

                prodInstDtoList.add(prodInstQryDto);
            });
        }
        if (!Objects.nonNull(rowCount)) {
            rowCount = prodInstDtoList.size();
        }
        //处理分页信息
        PageInfo<ProdInstQryDTO> resultPageInfo = new PageInfo<ProdInstQryDTO>();
        resultPageInfo.setList(prodInstDtoList);
        resultPageInfo.setPageNum(intpageNum);
        resultPageInfo.setPageSize(intPageSize);
        resultPageInfo.setTotal(rowCount);
        int pages = rowCount / intPageSize;
        if (rowCount % intPageSize != 0) {
            pages++;
        }
        resultPageInfo.setPages(pages);
        userQueryDto.setUserList(resultPageInfo);
        return userQueryDto;
    }

    @Override
    public CustOrderInfoRegion getProvince() {
        /**
         * 归属地属性根据工号级别不同，枚举值展示不同，譬如：
         * 集团工号可以查询全国的的用户，归属地的下拉框支持选择所有省分和地市，地市可允许为空；
         * 省级工号只能查询当前登录工号对应省分（包含本省所有地市及区县）的用户，归属地的下拉框省分默认当前登录工号对应省分，置灰不允许编辑，归属地的下拉框地市展示对应省分下的所有地市，允许编辑；
         * 市级工号只能查询当前登录工号对应地市（包含本地市及区县）的用户，归属地的下拉框省分默认当前登录工号对应省分，置灰不允许编辑，归属地的下拉框地市展示默认当前登录工号对应地市，置灰不允许编辑。
         */
        List<UnicomRegion> unicomRegions = unicomRegionService.listSubRegion("");
        CustOrderInfoRegion custOrderInfoRegion = new CustOrderInfoRegion();
        Long orgLevel = ContextUtil.getLoginInfo().getOrgInfo().getOrgLevel();
        String provinceCode = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        if (OrgLevel.BASE.getOrgLevel().equals(orgLevel)) {
            custOrderInfoRegion.setIsEdit(KeyConsts.IFTRUE_T);
        } else {
            custOrderInfoRegion.setIsEdit(KeyConsts.IFTRUE_F);
            unicomRegions.removeIf(unicomRegion -> !KiteStringUtils.isEqual(unicomRegion.getRegionCode(), provinceCode));
        }
        custOrderInfoRegion.setRegions(unicomRegions);
        if (unicomRegions.stream().anyMatch(unicomRegion -> KiteStringUtils.isEqual(unicomRegion.getRegionCode(), provinceCode))) {
            custOrderInfoRegion.setDefaultValue(provinceCode);
        } else {
            custOrderInfoRegion.setDefaultValue("");
        }
        return custOrderInfoRegion;
    }

    @Override
    public CustOrderInfoRegion getCity(String provinceCode) {
        CustOrderInfoRegion custOrderInfoRegion = new CustOrderInfoRegion();
        if (KiteStringUtils.isEmpty(provinceCode)) {
            return custOrderInfoRegion;
        }
        List<UnicomRegion> unicomRegions = unicomRegionService.listSubRegion(provinceCode);
        Long orgLevel = ContextUtil.getLoginInfo().getOrgInfo().getOrgLevel();
        String cityCode = ContextUtil.getLoginInfo().getUserInfo().getPostLanId();
        if (OrgLevel.BASE.getOrgLevel().equals(orgLevel) || OrgLevel.PROVINCE.getOrgLevel().equals(orgLevel)) {
            custOrderInfoRegion.setIsEdit(KeyConsts.IFTRUE_T);
        } else {
            custOrderInfoRegion.setIsEdit(KeyConsts.IFTRUE_F);
            unicomRegions.removeIf(unicomRegion -> !KiteStringUtils.isEqual(unicomRegion.getRegionCode(), cityCode));
        }
        custOrderInfoRegion.setRegions(unicomRegions);
        if (unicomRegions.stream().anyMatch(unicomRegion -> KiteStringUtils.isEqual(unicomRegion.getRegionCode(), cityCode))) {
            custOrderInfoRegion.setDefaultValue(cityCode);
        } else if (OrgLevel.PROVINCE.getOrgLevel().equals(orgLevel)) {
            custOrderInfoRegion.setDefaultValue(unicomRegions.get(0).getRegionCode());
        } else {
            custOrderInfoRegion.setDefaultValue("");
        }
        return custOrderInfoRegion;
    }

    /**
     * 获取甩单详情中客户编码和客户名称
     * @author zhang.song
     * @date 2021-08-30 10:40
     * @param orderId
     * @return com.iwhalecloud.bss.kite.cucc.client.dto.customerOrderInformation.OrderRejectionCust
     */
    @Override
    public OrderRejectionCust getOrderRejectionCust(String orderId) {
        Map<String, Object> orderDetailMap = orderService.getOrderDetail(orderId);
        Map<String, Object> customerMap = MapUtils.getMap(orderDetailMap, "CUSTOMER");
        OrderRejectionCust orderRejectionCust = new OrderRejectionCust();
        String custId = MapUtils.getString(customerMap, "GROUP_ID");
        String custName = MapUtils.getString(customerMap, "NAME");
        if(KiteStringUtils.isNotEmpty(custId)) {
            orderRejectionCust.setCustId(custId);
        } else if(KiteStringUtils.isNotEmpty(custName)) {
            orderRejectionCust.setCustName(custName);
        }

        List<Map> goods = CommonUtil.getList(orderDetailMap, "GOODS");
        if (KiteListUtils.isNotEmpty(goods)) {
            String catagoryId = MapUtils.getString(goods.get(0), "CATAGORY_ID");
            if(KiteStringUtils.isEmpty(catagoryId)) {
                String offerId = MapUtils.getString(goods.get(0), "CODE");
                catagoryId = Optional.ofNullable(OfferCache.get(offerId)).map(Offer::getCateId).orElse("");
            }

            List<DcPublic> dcPublics = DcPublicCache.getByPcode("20210914001", catagoryId);
            if(KiteListUtils.isNotEmpty(dcPublics)) {
                orderRejectionCust.setOrderCatagoryId(catagoryId);
            }
        }

        return orderRejectionCust;
    }
}
